package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.constant.ClueTrackRecordType;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.dpmain.clue.ClueDo;
import com.qk.dto.clue.ClueDto;
import com.qk.dto.clue.ClueFakeDto;
import com.qk.dto.clue.ClueListDto;
import com.qk.dto.clue.UpdateClueInfoDTO;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.ClueTrackRecordMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.ClueService;
import com.qk.vo.clue.ClueVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @文件名: ClueServiceImpl
 * @作者: DX
 * @创建日期: 2025/10/13
 * @描述:
 */
@Slf4j
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Override
    public PageResult<Clue> cluePollList(ClueListDto dto) {
        Page page = new Page<ClueListDto>(dto.getPage(), dto.getPageSize());
        Page<Clue> list = this.baseMapper.selectCluePollByPage(page, dto);
        return PageResult.<Clue>builder()
                .total(Long.valueOf(list.getTotal()).intValue())
                .rows(list.getRecords())
                .build();
    }

    @Transactional
    @Override
    public void toFake(Integer id , ClueFakeDto dto) {

        if(ObjectUtil.isEmpty(dto.getReason()) || ObjectUtil.isEmpty(id)){
            log.error("参数错误");
            CommonException.thowsCommonException(ParamEnum.PARAM_ENUM);
            return;
        }

        this.baseMapper.updateById(Clue.builder()
                .id(id)
                .updateTime(LocalDateTime.now())
                .status(ClueStatusConstants.PSEUDO_CLUE)
                .build());

        List<ClueTrackRecord> cts =  clueTrackRecordMapper.selectByClueId(id);

        for (ClueTrackRecord ct : cts) {
            this.clueTrackRecordMapper.updateById(ClueTrackRecord.builder()
                    .id(ct.getId())
                    .type(ClueTrackRecordType.FAKE)
                    .falseReason(dto.getReason())
                    .record(dto.getRemark())
                    .build());
        }
    }

    @Transactional
    @Override
    public void toBusiness(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        clue.setStatus(ClueStatusConstants.CONVERT_TO_BUSINESS);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);

        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setId(null);
        business.setNextTime(null);
        business.setUserId(null);
        business.setStatus(null);
        business.setUpdateTime(LocalDateTime.now());
        business.setCreateTime(LocalDateTime.now());
        this.businessMapper.insert(business);
    }
    @Transactional
    @Override
    public void updateClueInfoById(UpdateClueInfoDTO dto) {

        Clue clue = BeanUtil.copyProperties(dto, Clue.class);

        clue.setUpdateTime(LocalDateTime.now());

        if (dto.getStatus() == ClueStatusConstants.WAIT_FOLLOW_UP) {
            clue.setStatus(ClueStatusConstants.FOLLOW_UP);
        }
        this.baseMapper.updateById(clue);
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(dto, ClueTrackRecord.class);
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(clue.getId());
        clueTrackRecord.setType(ClueTrackRecordType.NORMAL);
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        this.clueTrackRecordMapper.insert(clueTrackRecord);
    }

    @Override
    public ClueVo getClueInfoById(Integer id) {

        Clue clue = this.baseMapper.selectById(id);

        Integer userId = clue.getUserId();
        User user = userMapper.getById(userId);

        List<ClueTrackRecord> clueTrackRecords = clueTrackRecordMapper.selectList(Wrappers.lambdaQuery(ClueTrackRecord.class)
                .in(ClueTrackRecord::getClueId, id)
        );

        ClueVo clueVO = BeanUtil.copyProperties(clue, ClueVo.class);
        List<ClueVo.ClueTrackRecordVo> list = clueTrackRecords.stream().map(item -> {
            ClueVo.ClueTrackRecordVo vo = BeanUtil.copyProperties(item, ClueVo.ClueTrackRecordVo.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();

        clueVO.setTrackRecords(list);
        return clueVO;
    }

    private PageResult<ClueDo> clueListMP(ClueListDto dto) {
        Page page = new Page<ClueListDto>(dto.getPage(), dto.getPageSize());
        Page<ClueDo> list = this.baseMapper.selectByPageMP(page, dto);
        return PageResult.<ClueDo>builder()
                .total(Long.valueOf(list.getTotal()).intValue())
                .rows(list.getRecords())
                .build();
    }

    @Override
    public PageResult<ClueDo> clueList(ClueListDto dto) {
//        PageHelper.startPage(dto.getPage(), dto.getPageSize());
//        Page<ClueDo> list = this.baseMapper.selectByPage(dto);
//        Page<ClueDo> page = ( Page<ClueDo>) list;
//        return PageResult.<ClueDo>builder()
//                .total(Long.valueOf(page.getTotal()).intValue())
//                .rows(page.getResult())
//                .build();
        return this.clueListMP(dto);
    }

    @Override
    public void addCule(ClueDto dto) {
        if (ObjectUtil.isEmpty(dto.getPhone()) || ObjectUtil.isEmpty(dto.getName())) {
            log.error("手机号或姓名不能为空");
            CommonException.thowsCommonException(ParamEnum.PARAM_ENUM);
        }


        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);

        this.save(clue);
    }
}
